<template>
  <div class="caseManage">
    <el-tabs v-model="activeName" type="card" class="elTabs">
      <el-tab-pane name="first">
        <div slot="label" class="pageHeader">案件立案管理</div>
      </el-tab-pane>
    </el-tabs>
    <div class="container">
      <!-- 搜索查询 -->
      <!-- <div class="searchBar" v-show="showSearch">
        <div class="searchForm">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="80px"
          >
            <el-form-item label="年份" prop="locationYear">
              <el-date-picker
                clearable
                v-model="queryParams.locationYear"
                type="year"
                value-format="yyyy"
                placeholder="请选择年份"
                @keyup.enter.native="handleQuery"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <div class="searchButtons">
          <el-button class="searchButton" @click="handleQuery">搜索</el-button>
          <el-button class="resetButton" @click="resetQuery">重置</el-button>
        </div>
      </div>-->

      <div
        class="addDeleteBar"
        v-if="
          checkPermi(['supervision:location:add', 'supervision:location:remove'])
        "
      >
        <el-button
          class="addButton"
          v-hasPermi="['supervision:location:add']"
          @click.native="handleAdd"
        >
          <span class="plus">+</span>
          新增
        </el-button>
        <el-button
          @click="handleDelete"
          :class="!multiple ? 'deleteButton' : 'allDeleteButton'"
          :disabled="multiple"
          icon="el-icon-delete"
          v-hasPermi="['supervision:location:remove']"
        >批量删除</el-button>
      </div>

      <!-- 表单选择清空 -->
      <div class="tableSelectArea">
        <div>
          <div class="iconInfo el-icon-info"></div>
          <span class="infoText">已选择</span>
          <span class="infoText infoActive" v-text="selectedNum"></span>
          <span class="infoText">项</span>
          <span class="infoButton" @click="clearSelect">清空</span>
        </div>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </div>
      <el-table v-loading="loading" :data="locationList" @expand-change="handleExpandChange">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table
              :data="props.row.location"
              style="width: 100%"
              :ref="'nestedTable' + props.row.bm"
              @selection-change="(selection) => handleSelectionChange(selection , props.row.bm)"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column prop="locationYear" label="年份" width="500" align="center"></el-table-column>
              <el-table-column prop="filcase" label="立案数" width="500" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <div class="tableButtonArea">
                    <el-button
                      type="text"
                      class="operationButton"
                      @click="handleDetail(scope.row)"
                    >详情</el-button>
                    <el-button
                      type="text"
                      class="operationButton"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['supervision:location:edit']"
                    >修改</el-button>
                    <el-button
                      type="text"
                      class="operationButton"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['supervision:location:remove']"
                    >删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="地区" align="left" prop="qc" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              class="line-style-button"
              v-hasPermi="['supervision:location:add']"
              @click.native="handleAdd(scope.row)"
            >
              <span class="plus">+</span>
              新增
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改案件立案区域分布对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="地区" prop="xzqhId">
            <el-select v-model="form.xzqhId" placeholder="请选择所属区域" clearable>
              <el-option v-for="qy in xzqhOptions" :key="qy.bm" :label="qy.qc" :value="qy.bm" />
            </el-select>
          </el-form-item>
          <el-form-item label="年份" prop="locationYear">
            <el-date-picker
              clearable
              v-model="form.locationYear"
              type="year"
              value-format="yyyy"
              placeholder="请选择年份"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="立案数" prop="filcase">
            <el-input type="number" v-model="form.filcase" placeholder="请输入立案数" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 详情对话框 -->
      <el-dialog title="详情" :visible.sync="openInfo" width="500px" append-to-body>
        <el-form ref="formInfo" :model="formInfo" label-width="100px" size="mini">
          <el-row>
            <el-col :span="12">
              <el-form-item label="地区：">
                {{
                formInfo.qc
                }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年份：">
                {{
                formInfo.locationYear
                }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="立案数：">{{ formInfo.filcase }}件</el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelInfo">关闭</el-button>
        </div>
      </el-dialog>
    </div>

    <locationDetailModal :detailId.sync="detailId"></locationDetailModal>

    <locationManageModal
      ref="chenManageModal"
      :modalType.sync="modalType"
      :id="id"
      :xzqhId="xzqhId"
      @fatherMethod="fatherMethod"
    ></locationManageModal>
  </div>
</template>

<script>
import { fatherMethod } from "@/utils/commonMethods";
import {
  listLocation,
  getLocation,
  delLocation,
  addLocation,
  updateLocation,
  getDistrict,
} from "@/api/caseManage/caseLocation/location";

import {
  MODALTYPE,
  CASESTATE,
  PAGESIZE,
  PAGENUM,
  DEPTTYPE,
  ROLETYPE,
  CASEEXPORTURL,
} from "@/utils/variable";

import locationManageModal from "./components/locationManageModal";
import locationDetailModal from "./components/locationDetailModal";
import { getChildXzqh } from "@/api/system/dept";

import { checkPermi, checkRole } from "@/utils/permission";

import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "Location",
  components: { Treeselect },
  components: { locationManageModal, locationDetailModal },
  data() {
    return {
      id: 0,
      xzqhId: "",
      //详情页Id
      detailId: 0,
      activeName: "first",
      selectedNum: 0,
      checkPermi,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 案件立案区域分布表格数据
      locationList: [],
      // 地区树选项
      xzqhOptions: [],
      selectedRows: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openInfo: false,
      modalType: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        locationYear: null,
      },
      // 表单参数
      form: {},
      formInfo: {},
      // 表单校验
      rules: {
        xzqhId: [{ required: true, message: "地区不能为空", trigger: "blur" }],
        locationYear: [
          { required: true, message: "年份不能为空", trigger: "blur" },
        ],
        filcase: [
          { required: true, message: "立案数不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    getChildXzqh("321").then((response) => {
      this.xzqhOptions = response.data;
    });
  },
  methods: {
    handleExpandChange(row) {
      let ids = this.ids;
      this.$nextTick(() => {
        // 获取折叠表格的 ref
        const nestedTable = this.$refs["nestedTable" + row.bm];
        if (nestedTable != null) {
          nestedTable.data.forEach((item) => {
            if (ids.includes(item.id)) {
              nestedTable.toggleRowSelection(item, true);
            }
          });
        }
      });
    },
    fatherMethod,
    /** 详情按钮操作 */
    handleDetail(row) {
      this.detailId = row.id;
    },
    /** 查询案件立案区域分布列表 */
    getList() {
      this.loading = true;
      listLocation(this.queryParams).then((response) => {
        this.locationList = response.rows;
        this.userMonthList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //清空列表选择
    clearSelect() {
      this.locationList.forEach((row) => {
        if (row.location) {
          row.location.forEach((subRow) => {
            const tableRef = this.$refs["nestedTable" + row.bm];
            if (tableRef && typeof tableRef.clearSelection === "function") {
              tableRef.clearSelection();
            }
          });
        }
      });
      // 数据初始化
      this.ids = [];
      this.selectedNum = 0; // 重置选中的项数
      this.multiple = true;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        xzqhId: null,
        locationYear: null,
        filcase: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelect: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection, rowId) {
      // this.selectedNum = selection.length;
      this.$set(this.selectedRows, rowId, selection);

      this.ids = [];
      for (const key in this.selectedRows) {
        if (Array.isArray(this.selectedRows[key])) {
          this.selectedRows[key].forEach((item) => {
            if (item && typeof item === "object" && "id" in item) {
              this.ids.push(item.id);
            }
          });
        }
      }
      this.selectedNum = this.ids.length;
      this.single = this.ids.length != 1;
      this.multiple = !this.ids.length;

      // this.ids = selection.map((item) => item.id);
      // this.single = selection.length != 1;
      // this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.modalType = MODALTYPE["新增"];
      this.xzqhId = row.bm;
      console.log("当前新增行数据为：", row);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.modalType = MODALTYPE["修改"];
      this.id = row.id;
      this.xzqhId = row.xzqhId;
    },
    /** 详情按钮操作 */
    handleInfo(row) {
      getLocation(row.id).then((response) => {
        this.formInfo = response.data;
        this.openInfo = true;
      });
    },
    /** 详情关闭按钮操作 */
    cancelInfo() {
      this.openInfo = false;
      this.formInfo = {};
      this.resetForm("formInfo");
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateLocation(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLocation(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let num = this.selectedNum;
      const ids = row.id || this.ids;
      if (row.id) {
        num = 1;
      }
      this.$modal
        .confirm("是否确认删除" + num + "条数据")
        .then(function () {
          return delLocation(ids);
        })
        .then(() => {
          this.getList();
          // 数据初始化
          this.ids = [];
          this.selectedNum = 0; // 重置选中的项数
          this.multiple = true;
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "supervision/location/export",
        {
          ...this.queryParams,
        },
        `location_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../assets/styles/variables.scss";
.caseManage {
  height: 100%;
  .tableFooter {
    text-align: right;
    justify-content: flex-end;
    // margin-top: 25px;
    margin-right: 35px;
    // width: 100%;
    ::v-deep .btn-prev {
      color: #d4d3d3 !important;
      background-color: #fff;
      border: 1px solid #d4d3d3;
    }
    ::v-deep .btn-next {
      color: #d4d3d3 !important;
      background-color: #fff;
      border: 1px solid #d4d3d3;
    }
    ::v-deep .el-pager li {
      background-color: #fff;
      border: 1px solid #d4d3d3;
      font-size: 12px;
      font-family: $font-family;
      font-weight: 400;
      color: #5a5b5d;
    }
  }
  .el-form-item__label {
    font-family: $font-family;
    font-weight: $form-label-font-weight;
    font-size: $form-label-font-size;
    color: $form-label-color;
  }

  .el-input__inner {
    font-size: $form-content-font-size;
    font-family: $font-family;
    font-weight: $form-label-font-weight;
    // color: #AEAFB0;
  }
}
.input {
  width: 150px;
}
::v-deep .el-tabs--card .el-tabs__header {
  background-color: #e4e7ed;
}
::v-deep.el-tabs--card .el-tabs__header .el-tabs__item {
  border-radius: 10px solid black;
  background-color: #fff;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #053ef6;
  line-height: 48px;
  margin-top: 0;
}

/* 确保嵌套表格宽度铺满 */
.el-table__body-wrapper {
  overflow: hidden;
}

.el-table__expand-icon {
  color: #409eff; /* 展开图标颜色 */
}

.el-table__body {
  background-color: #fff; /* 主表格背景颜色 */
}

.el-table__header th {
  background-color: #f5f7fa; /* 表头背景颜色 */
  font-weight: bold;
}

.el-button.addButton .plus {
  font-size: 14px;
}

.el-table .el-button {
  margin-right: 8px; /* 按钮之间的间距 */
}

.fixed-width {
  width: 120px; /* 设置固定宽度 */
}

.small-padding {
  padding: 4px 8px; /* 内边距优化 */
}
.line-style-button {
  background-color: #409eff;
  color: white;
  padding: 8px 4px !important;
}
</style>
